package com.kuzlak.cms.module.sys.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.extra.compress.CompressUtil;
import cn.hutool.extra.compress.archiver.Archiver;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kuzlak.cms.bean.Result;
import com.kuzlak.cms.constant.ResultConstant;
import com.kuzlak.cms.exception.SysErrorException;
import com.kuzlak.cms.handler.MyLambdaQueryWrapper;
import com.kuzlak.cms.libraries.Utils;
import com.kuzlak.cms.module.base.ThumbnailService;
import com.kuzlak.cms.module.sys.entity.SysPictures;
import com.kuzlak.cms.module.sys.service.SysPicturesService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import jakarta.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Hesenjan(Serkol)
 * @since 2021-11-18
 */
@Tag(name = "图片管理")
@RestController
@CrossOrigin
@RequestMapping("/api/pictures")
public class PicturesController {
    @Autowired
    private SysPicturesService picturesService;

    @Autowired
    private ThumbnailService thumbnailService;

    @Value("${upload.path}")
    private String uploadpath;
    @Value("${upload.host}")
    private String uploadhost;

    private static String getFileExtension(String name) {
        int extIndex = name.lastIndexOf(".");

        if (extIndex == -1) {
            return "";
        } else {
            return name.substring(extIndex + 1);
        }
    }

 /*   @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "图片上传", paramType = "formData", allowMultiple = true, required = true, dataType = "file"),
            @ApiImplicitParam(name = "folder", value = "文件夹", paramType = "query", dataType = "String")
    })*/
    @Operation(summary= "上传图片")
    @PostMapping(value = "/upload", headers = "content-type=multipart/form-data")
    public Result image(
            @RequestParam(name = "file") MultipartFile file,
            @RequestParam(name = "folder", defaultValue = "public") String folder, @RequestParam(name = "isType", defaultValue = "0") int isType) throws SysErrorException {
        Result result = new Result();
        folder = folder.replaceAll(",", "").trim();

        long request_id = System.currentTimeMillis();
        System.out.println("File:" + file.isEmpty());
        if (file.isEmpty()) {
            throw new NullPointerException("  Helllo ");
        }

        try {
            String format = DateUtil.format(new Date(), "yyyyMM");

            String contentType = file.getContentType();
            String type = getFileExtension(Objects.requireNonNull(file.getOriginalFilename()));
            BufferedImage bi = ImageIO.read(file.getInputStream());
            System.out.println(folder);
            String filem = "upload/" + format + "/" + folder + "/";
            String filemMini = "upload/" + format + "/" + folder + "/thumbnail/";
            System.out.println(filem);

            SysPictures pictures = new SysPictures();
            pictures.setIstype(isType);
            Random random = new Random();
            int i1 = random.nextInt(1000000000);
            int i11 = random.nextInt(1000);
            String fileName = filem + String.valueOf(System.currentTimeMillis()) + i1 + "." + type;
            String fileNameMini = filemMini + System.currentTimeMillis() + i1 + "." + type;
            String path = uploadhost + fileName;
            String pathname = uploadpath + fileName;
            String pathNameMini = uploadpath + fileNameMini;
            filem = uploadpath + filem;
            filemMini = uploadpath + filemMini;
            pictures.setName(Utils.quoteReplacement(file.getOriginalFilename()));
            System.out.println("bbbbbbbbbbbbb");
            System.out.println(bi);
            if (bi != null) {
                pictures.setH(bi.getHeight());
                pictures.setW(bi.getWidth());
            }
            pictures.setIstype(0);
            pictures.setType(type);
            pictures.setUrl(fileName);
            pictures.setImageUrl(fileNameMini);
            pictures.setRequestId((request_id + i11));
            //System.out.println(pictures.toString());
            //System.out.println(filem);
            //System.out.println(path);
            //System.out.println(pathname);
            boolean edit = picturesService.save(pictures);


            if (edit) {
                File file1 = new File(filemMini);

                if (!file1.exists()) {
                    file1.mkdirs();
                }
                File dest = new File(pathname);

                file.transferTo(dest);
                if (type.equals("jpg") || type.equals("jpeg") || type.equals("png")) {
                    thumbnailService.createThumbnail(pathname, pathNameMini, 400, 400);
                }
                //  result.setData(edit);
                QueryWrapper<SysPictures> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda()
                        .eq(SysPictures::getRequestId, pictures.getRequestId());
                //REQUEST_ID
                queryWrapper.last("LIMIT 1");

                SysPictures one = picturesService.getOne(queryWrapper);
                one.setUrl(uploadhost + "/" + one.getUrl());
                one.setImageUrl(uploadhost + "/" + one.getImageUrl());
                result.setData(one);
                result.setCode(ResultConstant.SUCSESS);
            } else {
                //result.setMsg(" hhh ");
                result.setCode(ResultConstant.FAIL);
            }


        } catch (IOException e) {
            e.printStackTrace();
            throw new SysErrorException(ResultConstant.FAIL);

        }


        return result;

    }

    @Operation(summary= "上传File")
    @PostMapping(value = "/uploadFile", headers = "content-type=multipart/form-data")
    public Result uploadFile(HttpServletRequest request,
                             @RequestParam(name = "file") MultipartFile file,
                             @RequestParam(name = "folder", defaultValue = "public") String folder, @RequestParam(name = "isType", defaultValue = "0") int isType) throws SysErrorException {
        Result result = new Result();


        long request_id = System.currentTimeMillis();
        //System.out.println("File:" + file.isEmpty());
        System.out.println(file.getOriginalFilename());
        if (file.isEmpty()) {
            throw new NullPointerException("  Helllo ");
        }

        try {
            String format = DateUtil.format(new Date(), "yyyyMM");

            String contentType = file.getContentType();

            String type = getFileExtension(Objects.requireNonNull(file.getOriginalFilename()));

            String filem = "upload/" + format + "/" + folder + "/";

            SysPictures pictures = new SysPictures();
            pictures.setIstype(isType);
            Random random = new Random();
            int i1 = random.nextInt(1000000000);
            int i11 = random.nextInt(1000);
            String fileName = filem + System.currentTimeMillis() + "yfsypt" + i1 + "." + type;
            String path = uploadhost + fileName;
            String pathname = uploadpath + fileName;
            filem = uploadpath + filem;

            pictures.setName(Utils.quoteReplacement(file.getOriginalFilename()));
            pictures.setIstype(0);
            pictures.setType(type);
            pictures.setUrl(fileName);
            pictures.setRequestId(request_id + i11);
            System.out.println(pictures);
            //System.out.println(filem);
            //System.out.println(path);
            //System.out.println(pathname);
            boolean edit = picturesService.save(pictures);


            if (edit) {
                File file1 = new File(filem);
                if (!file1.exists()) {
                    file1.mkdirs();
                }
                File dest = new File(pathname);

                file.transferTo(dest);
                //  result.setData(edit);
                QueryWrapper<SysPictures> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda()
                        .eq(SysPictures::getRequestId, pictures.getRequestId());
                //REQUEST_ID
                queryWrapper.last("LIMIT 1");

                SysPictures one = picturesService.getOne(queryWrapper);
                one.setUrl(uploadhost + "/" + one.getUrl());
                result.setData(one);
                result.setCode(ResultConstant.SUCSESS);
            } else {
                //result.setMsg(" hhh ");
                result.setCode(ResultConstant.FAIL);
            }


        } catch (IOException e) {
            e.printStackTrace();
            throw new SysErrorException(ResultConstant.FAIL);

        }


        return result;

    }

    @Operation(summary= "图片列表")
    @PostMapping("list")
    public Result list() {
        List<SysPictures> list = picturesService.list();
        return !list.isEmpty() ? Result.ok(list) : Result.failure(ResultConstant.EMPTIY);
    }

    @Operation(summary= "获取图片")
    @PostMapping("/geturl")
    public Result getUrl(@RequestParam(name = "id", defaultValue = "0") long id) throws SysErrorException {
        Result result = new Result();


        SysPictures byId = picturesService.getById(id);
        //System.out.println(byId);
        if (byId != null) {
            result.setCode(ResultConstant.SUCSESS);
            result.setData(uploadhost + "/" + byId.getUrl());
        } else {
            result.setCode(ResultConstant.EMPTIY);
        }

        return result;
    }

    @Operation(summary= "获取图片")
    @PostMapping("/geturls")
    public Result getUrls(@RequestParam(name = "ids", defaultValue = "0") String ids) throws SysErrorException {
        Result result = new Result();
        if (StringUtils.isNotEmpty(ids)) {
            System.out.println(ids);
            String[] idsd = ids.split(",");
            //  long[] idsd = StrUtil.splitToLong(",", ids);

            if (idsd.length > 0) {
                MyLambdaQueryWrapper<SysPictures> queryWrapper = new MyLambdaQueryWrapper<>();
                queryWrapper.in(SysPictures::getId, idsd);
                queryWrapper.select(SysPictures::getUrl);
                List<Object> mapList = picturesService.listObjs(queryWrapper);

                if (!mapList.isEmpty()) {
                    List<String> urls = mapList.stream().map(item -> (String) uploadhost + item).collect(Collectors.toList());
                    Map<String, Object> map = new HashMap<>();
                    map.put("url", uploadhost);
                    map.put("images", mapList);
                    result.setCode(ResultConstant.SUCSESS);
                    result.setData(urls);
                } else {
                    result.setCode(ResultConstant.EMPTY_DATA);
                }
            } else {
                result.setCode(ResultConstant.EMPTIY);
            }
        } else {
            result.setCode(ResultConstant.EMPTIY);
        }
        return result;
    }

    @Operation(summary= "删除图片")
    @PostMapping("/delete")
    public Result findByDelete(@RequestParam(name = "id", defaultValue = "0") long id) throws SysErrorException {
        Result result = new Result();
        if (id > 0) {
            SysPictures byId = picturesService.getById(id);
            if (byId != null) {
                String dir = uploadpath + byId.getUrl();
                File file = new File(dir);
                if (file.exists()) {
                    file.delete();
                }
                boolean b = picturesService.removeById(id);

                if (b) {
                    result.setCode(ResultConstant.SUCSESS);
                } else {
                    result.setCode(ResultConstant.EMPTIY);
                }
            } else {
                result.setCode(ResultConstant.EMPTIY);
            }
        } else {
            result.setCode(ResultConstant.EMPTIY);
        }

        return result;
    }


    @Operation(summary= "压缩文件")
    @PostMapping("/fileZip")
    public Result fileZip(@RequestParam(name = "ids", defaultValue = "0") String ids) throws SysErrorException {
        Result result = new Result();
        if (StringUtils.isNotEmpty(ids)) {
            System.out.println(ids);
            String[] idsd = ids.split(",");
            //  long[] idsd = StrUtil.splitToLong(",", ids);
            //   String idname = String.join("", idsd);
            if (idsd.length > 0) {
                MyLambdaQueryWrapper<SysPictures> queryWrapper = new MyLambdaQueryWrapper<>();
                queryWrapper.in(SysPictures::getId, idsd);
                queryWrapper.select(SysPictures::getUrl);
                List<Object> mapList = picturesService.listObjs(queryWrapper);

                if (!mapList.isEmpty()) {
                    Random random = new Random();
                    List<String> urls = mapList.stream().map(item -> (String) uploadpath + item).collect(Collectors.toList());
                    long l = System.currentTimeMillis();
                    int i1 = random.nextInt(1000000000);
                    String n = l + "L" + i1;
                    String filem = "archiver/zip/";
                    String lastPath = "archiver/zip/" + n + ".zip";
                    File file11 = new File(filem);
                    if (!file11.exists()) {
                        file11.mkdirs();
                    }

                    File file = FileUtil.file(uploadpath + lastPath);
                    System.out.println(file);
                    Archiver archiver = CompressUtil.createArchiver(CharsetUtil.CHARSET_UTF_8,"zip", file);
                    for (String next : urls) {
                        File file1 = FileUtil.file(next);
                        System.out.println(file1);
                        archiver
                                .add(file1);
                    }
                    archiver.finish()
                            .close();
                    File file1 = new File(file.getPath());
                    if (file1.exists()) {
                        String path = uploadhost + lastPath;

                        //    String normalize = URLUtil.normalize(path);
                        //  System.out.println(normalize);
                        result.setCode(ResultConstant.SUCSESS);
                        result.setData(path);
                    } else {
                        result.setCode(ResultConstant.FAIL);
                    }
                } else {
                    result.setCode(ResultConstant.EMPTY_DATA);
                }
            } else {
                result.setCode(ResultConstant.EMPTIY);
            }
        } else {
            result.setCode(ResultConstant.EMPTIY);
        }
        return result;
    }

}

